package de.tum.in.eist.poll.client.control;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.tum.in.eist.poll.client.gui.LoginPanel;
import de.tum.in.eist.poll.shared.User;

public class LoginHandler {

	private EIST_POLL eistPoll;
	private LoginPanel loginPanel;
	private AsyncCallback<User> callback;

	public LoginHandler(EIST_POLL eistPoll, LoginPanel loginPanel) {
		this.eistPoll = eistPoll;
		this.loginPanel = loginPanel;
		initCallback();
		setEventHandler();
	}

	/**
	 * Set different handler to the objects to handle key and mouse events
	 */
	private void setEventHandler() {
		// Button
		loginPanel.getLoginButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				// loginPanel.registrationWindow();

				// input check
				// input must be between 1 and 10 chars that are numbers,
				// letters, or dots.
				if (!inputIsValid(loginPanel.getNameTextbox().getText())
						|| !inputIsValid(loginPanel.getPasswordTextbox()
								.getText())) {
					Window.alert("User and password text must not contain special characters and has to be shorter than 255 characters.");
					loginPanel.getErrMessage().setHTML("Input must be numbers, letters, or dots");
				} 
				else {
					login();
				}
			}
		});

		// NameTextbox
		loginPanel.getNameTextbox().addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				loginPanel.getNameTextbox().selectAll();
			}
		});

		loginPanel.getNameTextbox().addKeyPressHandler(new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getCharCode() == KeyCodes.KEY_ENTER) {
					loginPanel.getPasswordTextbox().setFocus(true);
					loginPanel.getPasswordTextbox().selectAll();
				}
			}
		});

		// PasswordTextbox
		loginPanel.getPasswordTextbox().addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				loginPanel.getPasswordTextbox().selectAll();
			}
		});

		loginPanel.getPasswordTextbox().addKeyPressHandler(
				new KeyPressHandler() {
					@Override
					public void onKeyPress(KeyPressEvent event) {
						if (event.getCharCode() == KeyCodes.KEY_ENTER) {
							login();
						}
					}
				});
	}

	public boolean inputIsValid(String input) {
		if (input.contains("<") || input.contains(">") || input.contains(";")
				|| input.contains("{") || input.contains("}")
				|| input.contains("/") || input.length() >= 255) {
			return false;
		}
		return true;
	}

	/**
	 * try a login attempt
	 */
	protected void login() {
		EIST_POLL.pollSvc.login(loginPanel.getNameTextbox().getText(),
				loginPanel.getPasswordTextbox().getText(), callback);
	}

	/**
	 * initialize the {@link AsyncCallback} to react on faulty or successful
	 * login attempts
	 */
	private void initCallback() {
		callback = new AsyncCallback<User>() {

			@Override
			public void onFailure(Throwable caught) {
				loginPanel.getErrMessage().setHTML(caught.getMessage());
			}

			/**
			 * Login and load the next page
			 * 
			 * @param user
			 *            the User to login
			 */
			@Override
			public void onSuccess(User user) {
				loginPanel.getNameTextbox().addStyleName("anim");
				loginPanel.getPasswordTextbox().addStyleName("anim");
				loginPanel.getLoginButton().addStyleName("anim");
				loginPanel.getLoginPanelTitle().addStyleName("anim");

				eistPoll.setUser(user);
				loginPanel.getErrMessage().setHTML("");
				loginPanel.setHeight("0px");
				Cookies.setCookie("EIST_POLL_SESSIONID", user.getKey());

				Timer t = new Timer() {
					@Override
					public void run() {
						eistPoll.loadDashboard();
					}
				};
				t.schedule(500);
			}
		};
	}
}
